import BackPage from '@/components/BackPage';
import SaleBadge from '@/components/SaleBadge';
import { addSaleContent, allEvaluateByCompany } from '@/services/evaluate';
import { getQueryParams } from '@/utils/utils';
import { FrownOutlined, MehOutlined, SmileOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Avatar, Button, Input, message, Modal, Rate } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useRef, useState } from 'react';
import styles from './index.less';

const Assessment: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [assessmentModal, setAssessmentModal] = useState<boolean>(false);
  const [contentCurrent, setContentCurrent] = useState<string>('');
  const [contentSale, setContentSale] = useState<string>('');
  const [rate, setRate] = useState<any>({});
  const [inputValue, setInputValue] = useState<string>('');
  const [idCurrent, setIdCurrente] = useState<string>('');
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const { TextArea } = Input;
  const qs = getQueryParams();
  const [ifReplyContent, setIfReplyContent] = useState<boolean>(false);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  const customIcons: Record<number, React.ReactNode> = {
    1: <FrownOutlined style={{ fontSize: 14 }} />,
    2: <FrownOutlined style={{ fontSize: 14 }} />,
    3: <MehOutlined style={{ fontSize: 14 }} />,
    4: <SmileOutlined style={{ fontSize: 14 }} />,
    5: <SmileOutlined style={{ fontSize: 14 }} />,
  };

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      const res = await allEvaluateByCompany({ companyid: qs.id, pageIndex: currentPage });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage, qs.id]);

  useEffect(() => {
    getList();
  }, [getList]);

  const addedSaleContent = async () => {
    if (inputValue !== '') {
      await addSaleContent({ id: idCurrent, companycontent: inputValue, ifreply: '1' }).then(() => {
        setAssessmentModal(false);
        setContentCurrent('');
        setInputValue('');
        getList();
        message.success('回复成功！');
      });
    } else {
      message.error('请输入回复内容！');
    }
  };

  // const removeContent = async (id: string) => {
  //   await removeEvaluate({ id: id }).then(() => {
  //     getList();
  //   });
  // };

  const onChangeInput = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    let value = e.target.value;
    setInputValue(value);
  };

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '订单编号',
      dataIndex: 'id',
      copyable: true,
      ellipsis: true,
      // tip: '标题过长会自动收缩',
    },
    {
      title: '买家昵称',
      dataIndex: 'username',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'ifreply',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        all: { text: '超长'.repeat(50) },
        '0': {
          text: '未回复',
          status: 'Error',
        },
        '1': {
          text: '已回复',
          status: 'Success',
          disabled: true,
        },
      },
    },
    {
      title: '评价星级',
      copyable: true,
      render: (text, record) => [
        <Rate
          key={record.id}
          defaultValue={record.star}
          character={({ index }: any) => customIcons[index + 1]}
          disabled
        />,
      ],
    },
    {
      title: '评价内容',
      dataIndex: 'usercontent',
      copyable: true,
      ellipsis: true,
      render: (text, record) => [
        <div
          key={record.id}
          style={{ cursor: 'pointer' }}
          onClick={() => {
            setAssessmentModal(true);
            setContentCurrent(record.usercontent);
            setRate(record);
            if (record.companycontent) {
              setIfReplyContent(true);
              setContentSale(record.companycontent);
            } else {
              setIfReplyContent(false);
            }
          }}
        >
          {record.usercontent}
        </div>,
      ],
    },
    {
      title: '评价时间',
      key: 'timeadd',
      dataIndex: 'timeadd',
      render: (text, record) => [
        <div key={record.id}>{`${moment(Number(record.timeadd)).format(
          'YYYY-MM-DD HH:mm:ss',
        )}`}</div>,
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <>
          {record.companycontent ? (
            <div
              key={record.id}
              className={styles.delete}
              style={{ border: `1px solid ${colorThem}`, color: colorThem, cursor: 'not-allowed' }}
            >
              已回复
            </div>
          ) : (
            <div
              key={record.id}
              className={styles.delete}
              onClick={() => {
                setAssessmentModal(true);
                setContentCurrent(record.usercontent);
                setIdCurrente(record.id);
                setRate(record);
              }}
              style={{ border: `1px solid ${colorThem}`, color: colorThem, cursor: 'pointer' }}
            >
              回复
            </div>
          )}
          {/* <div
            key={record.id}
            className={styles.delete}
            onClick={() => {
              removeContent(record.id);
            }}
            style={{ border: `1px solid ${colorThem}`, color: colorThem, cursor: 'pointer' }}
          >
            删除
          </div> */}
        </>,
      ],
    },
  ];

  return (
    <BackPage thisRoute={'/assessment'} lastRoute={'评价管理'}>
      <div className={styles.container}>
        <ProTable<any>
          columns={columns}
          actionRef={actionRef}
          cardBordered={false}
          dataSource={list}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        <Modal
          visible={assessmentModal}
          onCancel={() => {
            setAssessmentModal(false);
            setContentCurrent('');
          }}
          footer={[
            <>
              {!ifReplyContent && (
                <Button
                  style={{ backgroundColor: colorThem, color: '#fff' }}
                  className={styles.sendBtn}
                  key={'true'}
                  onClick={() => {
                    addedSaleContent();
                  }}
                >
                  回复
                </Button>
              )}
              <Button
                style={{ backgroundColor: '#fff', color: colorThem }}
                key={'false'}
                onClick={() => {
                  setAssessmentModal(false);
                  setContentCurrent('');
                }}
              >
                关闭
              </Button>
            </>,
          ]}
        >
          <div className={styles.modalContentTop}>
            <div>
              <Avatar
                size={68}
                shape="square"
                src={`http://localhost:8090/dyh/upload_images/user/${rate.avatar}`}
                style={{
                  marginRight: 10,
                  cursor: 'context-menu',
                }}
              />
            </div>
            <div>
              <div style={{ marginBottom: 8, fontWeight: 600 }}>
                买家评价：
                <Rate
                  value={rate.star}
                  character={({ index }: any) => customIcons[index + 1]}
                  disabled
                />
              </div>
              {contentCurrent}
            </div>
          </div>
          <div style={{ margin: '40px 0 20px 0' }}>
            <div style={{ marginBottom: 5, fontWeight: 600 }}>您的回复：</div>
            {ifReplyContent ? (
              <div>{contentSale}</div>
            ) : (
              <TextArea
                maxLength={300}
                value={inputValue}
                onChange={onChangeInput}
                placeholder={'请输入您的回复...'}
                bordered={false}
                autoSize={{ minRows: 9, maxRows: 9 }}
                showCount
              />
            )}
          </div>
        </Modal>
        <SaleBadge />
      </div>
    </BackPage>
  );
};
export default Assessment;
